﻿using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
using XCI.Core;
using XCI.Extensions;
using XCI.Helper;

namespace XCI.Windows
{
    public partial class CategoryFileUploadControl : BaseUserControl
    {
        private string editValue;
        private readonly Font font = new Font(WindowsFormsSettings.DefaultFont.Name, 16f);
        private readonly SolidBrush brush = new SolidBrush(Color.Red);

        public CategoryFileUploadControl()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 文件上传控件显示模式
        /// </summary>
        [Category("XCI")]
        [Description("文件上传控件显示模式")]
        [DefaultValue(FileUploadControlShowMode.View)]
        public FileUploadControlShowMode ShowMode { get; set; } = FileUploadControlShowMode.View;

        /// <summary>
        /// 文件分组字典编码
        /// </summary>
        [Category("XCI")]
        [Description("文件分组字典编码")]
        [DefaultValue(null)]
        public string DicCode { get; set; }

        /// <summary>
        /// 文件分组上下间距
        /// </summary>
        [Category("XCI")]
        [Description("文件分组上下间距")]
        [DefaultValue(10)]
        public int CategoryMarginTop { get; set; } = 10;

        /// <summary>
        /// 文件分组面板高度
        /// </summary>
        [Category("XCI")]
        [Description("文件分组面板高度")]
        [DefaultValue(200)]
        public int GroupControlHeight { get; set; } = 200;

        /// <summary>
        /// 当无匹配的分组时显示其他分组
        /// </summary>
        [Category("XCI")]
        [Description("当无匹配的分组时显示其他分组")]
        [DefaultValue(true)]
        public bool ShowOtherCategory { get; set; } = true;

        /// <summary>
        /// 是否显示工具栏
        /// </summary>
        [Browsable(true), Category("XCI"), Description("是否显示工具栏"), DefaultValue(true)]
        public bool ToolbarVisable { get; set; } = true;

        /// <summary>
        /// 上传子文件夹（默认自动获取）
        /// </summary>
        [Browsable(true), Category("XCI"), Description("上传子文件夹（默认自动生成）"), DefaultValue(null)]
        public string UploadFolder { get; set; }

        /// <summary>
        /// 上传成功后保存到附件表
        /// </summary>
        [Browsable(true), Category("XCI"), Description("上传成功后保存到附件表"), DefaultValue(true)]
        public bool AutoSaveToFileTable { get; set; } = true;

        /// <summary>
        /// 是否允许添加目录
        /// </summary>
        [Browsable(true), Category("XCI"), Description("是否允许添加目录"), DefaultValue(true)]
        public bool AllowAddFolder { get; set; } = true;

        /// <summary>
        /// 是否允许添加快捷方式
        /// </summary>
        [Browsable(true), Category("XCI"), Description("是否允许添加快捷方式"), DefaultValue(true)]
        public bool AllowAddShortcut { get; set; } = true;

        /// <summary>
        /// 允许文件上传的扩展名,不含点,逗号隔开
        /// </summary>
        [Category("XCI"), Description("许文件上传的扩展名,不含点,逗号隔开"), DefaultValue(FileUploadControl.ALLOW_EXTENSION_NAME)]
        public string AllowFileExtension { get; set; } = FileUploadControl.ALLOW_EXTENSION_NAME;

        /// <summary>
        /// 最多允许的文件数量
        /// </summary>
        [Category("XCI"), Description("最多允许的文件数量"), DefaultValue(99)]
        public int MaxFileCount { get; set; } = 99;

        /// <summary>
        /// 单个文件允许的最大值,单位KB,默认10M
        /// </summary>
        [Category("XCI"), Description("单个文件允许的最大值,单位KB,默认10M"), DefaultValue(10240)]
        public int SingleFileMaxSize { get; set; } = 10240;

        /// <summary>
        /// 是否自动下载图片文件
        /// </summary>
        [Browsable(true), Category("XCI"), Description("是否自动下载图片文件"), DefaultValue(true)]
        public bool AutoDownloadImage { get; set; } = true;

        /// <summary>
        /// 获取或设置记录主键。
        /// </summary>
        [Category("XCI"), Description("获取或设置记录主键。")]
        [Browsable(false), Bindable(true), DefaultValue(null)]
        public string EditValue
        {
            get { return editValue; }
            set
            {
                editValue = value;
                LoadData();
            }
        }

        public void LoadData()
        {
            if (DicCode.IsEmpty())
            {
                MessageBoxHelper.ShowError("请指定文件分组字典编码");
                return;
            }

            //if (editValue.IsEmpty())
            //{
            //    MessageBoxHelper.ShowError("请指定上传关联的记录Id");
            //    return;
            //}
            //var fileList = FileService.Instance.SelectPageListAsync(editValue);
            ////this.SuspendLayout();
            //foreach (Control control in this.Controls)
            //{
            //    control.Dispose();
            //}
            //this.Controls.Clear();
            //var dicList = DicService.Instance.GetDicListFromCache(DicCode);
            //var createdList = new List<CategoryFileUploadCreateItem>();
            //for (int i = 0; i < dicList.Count; i++)
            //{
            //    var dic = dicList[i];
            //    var files = fileList.Where(p => p.Category != null && p.Category == dic.Value).ToList();
            //    fileList.RemoveIf(p => files.ContainsIf(x => x.Id == p.Id));
            //    createdList.Add(new CategoryFileUploadCreateItem { Files = files, Dic = dic });
            //}
            //if (fileList.Count > 0 && ShowOtherCategory)
            //{
            //    createdList.Add(new CategoryFileUploadCreateItem { Files = fileList, Dic = new SysDic { Id = "other", Name = "其他", Value = "other" } });
            //}

            ////翻转集合,后添加的优先级高
            //createdList.Reverse();
            //createdList.ForEach(Create);
        }

        private void Create(CategoryFileUploadCreateItem item)
        {
            // List<SysFile> files = item.Files;
            // SysDic dic = item.Dic;
            var fileUploadControl = new FileUploadControl();
            fileUploadControl.Dock = DockStyle.Fill;
            // AsyncHelper.RunSync(() => fileUploadControl.SetFile(editValue, files));

            fileUploadControl.ToolbarVisable = ToolbarVisable;
            fileUploadControl.UploadFolder = UploadFolder;
            fileUploadControl.AutoSaveToFileTable = AutoSaveToFileTable;
            fileUploadControl.AllowAddFolder = AllowAddFolder;
            fileUploadControl.AllowAddShortcut = AllowAddShortcut;
            fileUploadControl.AllowFileExtension = AllowFileExtension;
            fileUploadControl.MaxFileCount = MaxFileCount;
            fileUploadControl.SingleFileMaxSize = SingleFileMaxSize;
            fileUploadControl.AutoDownloadImage = AutoDownloadImage;
            fileUploadControl.UploadButton.Visibility = BarItemVisibility.Never;

            if (ShowMode == FileUploadControlShowMode.View)
            {
                fileUploadControl.SelectButton.Visibility = BarItemVisibility.Never;
                fileUploadControl.RemoveButton.Visibility = BarItemVisibility.Never;
            }
            else
            {
                fileUploadControl.SelectButton.Visibility = BarItemVisibility.Always;
                fileUploadControl.RemoveButton.Visibility = BarItemVisibility.Always;
            }

            // var groupControl = new DevExpress.XtraEditors.GroupControl();
            // groupControl.Controls.Add(fileUploadControl);
            // if (dic.Remark.IsNotEmpty())
            // {
            //     //添加Label,后添加的优先级高
            //     groupControl.Controls.Add(new LabelControl
            //     {
            //         Name = "remark" + dic.Id,
            //         Dock = DockStyle.Top,
            //         Location = new Point(0, 0),
            //         Text = dic.Remark,
            //         Padding = new Padding(5, 10, 5, 10)
            //     });
            // }
            //
            // groupControl.Dock = DockStyle.Top;
            // groupControl.Size = new Size(this.Width, GroupControlHeight);
            // groupControl.Location = new Point(0, 0);
            // groupControl.Name = dic.Id;
            // groupControl.Tag = dic.Value;
            // groupControl.Text = dic.Name;
            //
            // var f = groupControl.AppearanceCaption.Font;
            // groupControl.AppearanceCaption.Font = new Font(f.Name, f.Size + 3);
            // if (Controls.Count > 0)
            // {
            //     this.Controls.Add(new LabelControl
            //     {
            //         Name = "margin" + dic.Id,
            //         Dock = DockStyle.Top,
            //         Location = new Point(0, 0),
            //         Text = string.Empty,
            //         AutoSizeMode = LabelAutoSizeMode.None,
            //         Size = new Size(groupControl.Width, CategoryMarginTop)
            //     });
            // }
            // this.Controls.Add(groupControl);
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        public async Task<BoolResult<FileUploadEventArgs>> UploadFileAsync(string recordId = null)
        {
            if (!string.IsNullOrEmpty(recordId))
            {
                this.editValue = recordId;
            }
            if (editValue.IsEmpty())
            {
                return new BoolResult<FileUploadEventArgs>(false, "请指定上传关联的记录Id");
            }
            var results = new List<BoolResult<FileUploadEventArgs>>();
            foreach (var item in this.Controls)
            {
                if (!(item is GroupControl)) continue;
                GroupControl group = item as GroupControl;
                foreach (var control in group.Controls)
                {
                    if (!(control is FileUploadControl)) continue;
                    var uploadControl = control as FileUploadControl;
                    results.Add(await uploadControl.UploadFileAsync(editValue, group.Tag.ToStringOrEmpty()));
                }
            }

            return BoolResult<FileUploadEventArgs>.Merge(results.ToArray());
        }

        private void CategoryFileUploadControl_Paint(object sender, PaintEventArgs e)
        {
            if (WinFormHelper.IsDesignMode())
            {
                e.Graphics.DrawRectangle(new Pen(brush), new Rectangle(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 1));
                DrawHelper.DrawStringAsCenter(e.Graphics, "附件分组控件", font, brush, ClientRectangle);
            }
        }
    }

    public class CategoryFileUploadCreateItem
    {
        // public List<SysFile> Files { get; set; }
        // public SysDic Dic { get; set; }
    }

    /// <summary>
    /// 文件上传控件显示模式
    /// </summary>
    public enum FileUploadControlShowMode
    {
        /// <summary>
        /// 编辑模式
        /// </summary>
        Edit,

        /// <summary>
        /// 查看模式
        /// </summary>
        View
    }
}
